<template>
  <div>
    <input 
      type="file" 
      id="hiddenFileInput" 
      @change="onFileChange" 
      style="display: none;" 
      ref="fileInput" 
    />
    <div>
      <img class="img" v-if="previewImage" :src="previewImage" alt="预览图片" />
    </div>
    <el-button @click="triggerFileInput" plain size="small">{{previewImage ? '重新上传' : '选择文件'}}</el-button>
    <el-button type="danger" @click="handleDel" size="small" v-if="previewImage" plain>删除</el-button>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      previewImage: this.value
    };
  },
  watch: {
    value(newValue) {
      this.previewImage = newValue;
      // 同步清空input值
      this.clearFileInput();
    }
  },

  methods: {
    onFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewImage = e.target.result;
          this.$emit('update:value', this.previewImage);
        };
        reader.onerror = () => {
          console.error('文件读取失败');
          this.$emit('error', '文件读取失败');
        };
        reader.readAsDataURL(file);
      }
    },
    triggerFileInput() {
      // 先清空input值再触发
      this.clearFileInput();
      this.$refs.fileInput.click();
    },
    handleDel() {
      this.previewImage = '';
      this.$emit('update:value', '');
      // 删除时同步清空input值
      this.clearFileInput();
    },
    clearFileInput() {
      const input = this.$refs.fileInput;
      if (input) {
        input.value = '';
      }
    }
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
button {
  padding: 10px 20px;
  background-color: #2262FB;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.img {
  max-width: 100px;
  height: auto;
}
</style>